//
//  LoginVIewController.m
//  who
//
//  Created by yunqi-dev-1 on 15/8/25.
//  Copyright (c) 2015年 yunqi-dev-1. All rights reserved.
//

#import "LoginVIewController.h"
#import "AppDelegate.h"
#import "DXKit.h"

@implementation LoginVIewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.PassWordTextField.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.title = @"登陆";
    self.navigationController.navigationBarHidden = YES;
}

- (IBAction)clickLogin:(UIButton *)sender {
    if (self.userNameTextField.text.length == 0) {
        [DX alert:@"请填写用户名"];
        return;
    }
    
    if (self.PassWordTextField.text.length == 0) {
        [DX alert:@"请输入密码"];
        return;
    }
    NSDictionary *params = @{@"phone":self.userNameTextField.text, @"password":self.PassWordTextField.text};
    [DX POST:API_ACTION_USER_LOGIN parameters:params controller:self success:^(NSDictionary *response) {
        NSNumber *code = response[@"code"];
        NSString *token = response[@"token"];
        NSDictionary *user = response[@"user"];
        if (code.integerValue == 0 && token.length != 0 && user)
        {
            DXData *data = [DXData sharedInstance];
            data.token = token;
            data.user = [user mutableCopy];
            
            [data save];
            
            [[AppDelegate getAppDelegate] refreshRootViewControllerWithStoryboardName:@"main" animation:YES];
        }
        else
        {
            if (code.integerValue == ERROR_WRONG_NAME)
            {
                [DX alert:@"用户名无效"];
            }
            else if (code.integerValue == ERROR_WRONG_PASSWORD)
            {
                [DX alert:@"密码错误"];
            }
            else if(code.integerValue == ERROR_NOT_EXIST)
            {
                [DX alert:@"用户不存在"];
            }
        }
    } failure:^(NSError *error) {
    } failureAlert:YES];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.PassWordTextField resignFirstResponder];
    [self.userNameTextField resignFirstResponder];
}

@end
